﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SmartProduction.Domain.采购委外订单;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Write.API.Application.Commands.PurchaseCommand;

namespace SmartProduction.Write.API.Application.CommandHandlers.PurchaseCommandHandler
{
    /// <summary>
    /// 采购/委外编辑命令处理
    /// </summary>
    public class PurchaseUpdatedetailsUpdateCommandHandler : IRequestHandler<PurchaseUpdatedetailsUpdateCommand, APIResult<object>>
    {
        /// <summary>
        /// AutoMapper
        /// </summary>

        private readonly IMapper mapper;
        /// <summary>
        /// 采购
        /// </summary>
        private readonly IBaseRepository<Purchase> purchaseRepository;
        /// <summary>
        /// 详情
        /// </summary>
        private readonly IBaseRepository<Purchasedetails> purchaseDetailsRepository;

        public PurchaseUpdatedetailsUpdateCommandHandler(IMapper mapper, IBaseRepository<Purchase> purchaseRepository, IBaseRepository<Purchasedetails> purchaseDetailsRepository)
        {
            this.mapper = mapper;
            this.purchaseRepository = purchaseRepository;
            this.purchaseDetailsRepository = purchaseDetailsRepository;
        }

        public async Task<APIResult<object>> Handle(PurchaseUpdatedetailsUpdateCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            var purchase = purchaseRepository.GetAll().Result.Where(o => o.OrderCode == request.OrderCode).FirstOrDefault();
            purchase.Purchaseid = request.Purchaseid;
            purchase.OrderCode = request.OrderCode;
            purchase.OrderName = request.OrderName;
            purchase.OrderType = request.OrderType;
            purchase.Project = request.Project;
            purchase.Supplier = request.Supplier;
            purchase.SignDate = request.SignDate;
            purchase.Maker = request.Maker;
            purchase.MakerDept = request.MakerDept;
            purchase.Status = request.Status;
            purchase.ApprovalStatus = request.ApprovalStatus;
            purchase.AgreementCode = request.AgreementCode;
            purchase.AgreementName = request.AgreementName;
            purchase.OrderRemark = request.OrderRemark;
            purchase.OrderAmount = request.OrderAmount;
            purchase.Currency = request.Currency;
            purchase.AdvancePayment = request.AdvancePayment;
            purchase.OrderStartDate = request.OrderStartDate;
            purchase.OrderEndDate = request.OrderEndDate;
            purchase.SignTime = request.SignTime;
            purchase.TaxType = request.TaxType;
            purchase.TaxRate = request.TaxRate;
            purchase.InvoiceAmount = request.InvoiceAmount;
            purchase.PaidAmount = request.PaidAmount;
            var res = purchaseRepository.UpdateAsync(purchase).Result;
            if (res > 0)
            {

                try
                {
                    // 1. 正确异步调用链
                    var query = await purchaseDetailsRepository.GetAll(); // 假设GetAll()返回Task<IQueryable<T>>
                    var detailsToDelete = await query
                        .Where(d => d.POrderCode == request.OrderCode)    // 修正Lambda表达式
                        .ToListAsync();                                   // 修正拼写

                    // 2. 空集合防御
                    if (detailsToDelete?.Count > 0)
                    {
                        // 3. 使用批量删除方法
                        var deleteResult = await purchaseDetailsRepository.DeleteRemove(detailsToDelete);

                        // 4. 结果验证
                        result.Code = deleteResult == detailsToDelete.Count
                            ? APIEnums.删除成功
                            : APIEnums.删除成功;
                        result.Msg = $"{result.Code} ({deleteResult}/{detailsToDelete.Count})";
                    }
                    else
                    {
                        result.Code = APIEnums.删除失败;
                        result.Msg = "未找到可删除记录";
                    }
                }
                catch (Exception ex)
                {
                    result.Code = APIEnums.删除失败;
                    result.Msg = $"删除异常: {ex.Message}";
                }

                var detailsToAdd = new List<Purchasedetails>(); // 创建集合保存所有明细
                foreach (var item in request.Purchasedetailss)
                {
                    // 每次循环创建新对象
                    var detail = new Purchasedetails
                    {
                        PurchaseId = item.PurchaseId,
                        MaterialCode = item.MaterialCode,
                        MaterialName = item.MaterialName,
                        UnitPrice = item.UnitPrice,
                        Quantity = item.Quantity,
                        Unit = item.Unit,
                        Amount = item.Amount,
                        Abstract = item.Abstract,
                        MaterialId = item.MaterialId,
                        POrderCode = request.OrderCode,
                        CreatedTime = DateTime.Now
                    };
                    detailsToAdd.Add(detail);
                }
                if (detailsToAdd.Count > 0)
                {
                    try
                    {
                        var res3 = await purchaseDetailsRepository.AddRanges(detailsToAdd);
                        if (res3 == detailsToAdd.Count)
                        {
                            result.Code = APIEnums.修改成功;
                            result.Msg = $"{APIEnums.修改成功} (新增{res3}条)";
                            result.data = new { mainRes = res, detailRes = res3 };
                        }
                        else
                        {
                            result.Code = APIEnums.修改成功;
                            result.Msg = $"主记录更新成功，但只插入了{res3}/{detailsToAdd.Count}条明细";
                        }
                    }
                    catch (Exception ex)
                    {
                        result.Code = APIEnums.修改失败;
                        result.Msg = $"明细插入失败: {ex.Message}";
                    }

                }
            }
            else
            {
                result.Code = APIEnums.修改失败;
                result.Msg = APIEnums.修改失败.ToString();
                result.data = res;
            }
            return await Task.FromResult(result);
        }

    }
}
